package com.example.sunflowers.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import cn.trans88.taxiappkotlin.ext.logd
import com.example.sunflowers.data.db.Plant
import com.example.sunflowers.data.repository.PlantRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 *
 * @Author： LJH
 * @Time： 2024/1/30
 * @description：
 */
@HiltViewModel
class PlantListViewModel @Inject internal constructor(
    plantRepository:PlantRepository,
    private val savedStateHandle: SavedStateHandle
) :ViewModel(){

    companion object{
        private const val NO_GROW_ZONE = -1
        private const val GROW_ZONE_SAVED_STATE_KEY = "GROW_ZONE_SAVED_STATE_KEY"
    }

    private val growZone:MutableStateFlow<Int> = MutableStateFlow(
        savedStateHandle.get(GROW_ZONE_SAVED_STATE_KEY) ?: NO_GROW_ZONE
    )

    init {
        viewModelScope.launch {
            growZone.collect{ newGrowZone ->
                savedStateHandle.set(GROW_ZONE_SAVED_STATE_KEY,newGrowZone)
            }
        }
    }

    val plants:LiveData<List<Plant>> = growZone.flatMapLatest { zone ->
        "flatMapLatest run了".logd()
        if (zone == NO_GROW_ZONE){
            "gatPlants".logd()
            plantRepository.getPlants()
        } else {
            "getPlantWithGrowZoneNumber".logd()
            plantRepository.getPlantWithGrowZoneNumber(zone)
        }
    }.asLiveData()

    fun setGrowZoneNumber(num:Int){
        growZone.value = num
    }

    fun clearGrowZoneNumber(){
        growZone.value = NO_GROW_ZONE
    }

    fun isFiltered() = growZone.value != NO_GROW_ZONE

}